import dayjs from 'dayjs';
import Cache from 'js-cookie';

interface SaveData {
  value: string | object;
  expires: number;
}

/**
 * @description: 设置缓存
 * @param {string} key
 * @param {string | object} value
 * @param {number} [expires=30] 为 0 表示永不过期
 */
export const setStorage = (
  key: string,
  value: string | object,
  expires?: number
) => {
  const expiresDate = dayjs()
    .add(expires || 30, 'days')
    .unix();
  const data = JSON.stringify({
    value,
    expires: expiresDate
  });
  if (localStorage) {
    localStorage.setItem(key, data);
  } else {
    Cache.set(key, data);
  }
};

/**
 * @description: 获取缓存
 * @param {string} key
 * @returns {T | undefined}
 */
export const getStorage = <T extends object | string>(
  key: string
): T | undefined => {
  let ss: string | undefined;
  if (localStorage) {
    ss = localStorage.getItem(key) ?? undefined;
  } else {
    ss = Cache.get(key);
  }
  if (!ss) return undefined;
  try {
    const { expires, value } = JSON.parse(ss) as SaveData;
    if (expires == 0) {
      return value as T;
    }
    const expiresDate = dayjs.unix(expires);
    if (expiresDate.isBefore(dayjs())) return undefined;
    return value as T;
  } catch (error) {
    clearStorage();
    console.error(error);
    return undefined;
  }
};

export const removeStorage = (key: string) => {
  if (localStorage) {
    localStorage.removeItem(key);
  } else {
    Cache.remove(key);
  }
};

export const clearStorage = () => {
  if (localStorage) {
    localStorage.clear();
  } else {
    const info = Cache.get();
    Object.keys(info).forEach((key) => {
      Cache.remove(key);
    });
  }
};
